package com.hbzhou.open.camera.slice;

import com.hbzhou.open.camera.MainAbility;
import com.hbzhou.open.camera.listener.PermissionInterface;
import com.hbzhou.open.camera.ResourceTable;
import com.hbzhou.open.flowcamera.JCameraView;
import com.hbzhou.open.flowcamera.listener.JCameraListener;
import com.hbzhou.open.flowcamera.util.FileUtil;
import com.hbzhou.open.flowcamera.util.LogUtil;
import com.hbzhou.open.flowcamera.util.ResUtils;
import com.hbzhou.open.flowcamera.util.ScreenUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.StackLayout;
import ohos.bundle.AbilityInfo;
import ohos.event.commonevent.CommonEventData;
import ohos.event.commonevent.CommonEventManager;
import ohos.media.image.PixelMap;
import ohos.rpc.RemoteException;
import ohos.security.SystemPermission;
import ohos.utils.net.Uri;

import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import static ohos.bundle.IBundleManager.PERMISSION_GRANTED;

/**
 * MainAbilitySlice
 */
public class MainAbilitySlice extends AbilitySlice implements PermissionInterface {
    public static final String ACTION_MEDIA_SCANNER_SCAN_FILE = "android.intent.action.MEDIA_SCANNER_SCAN_FILE";

    private JCameraView mJCameraView;

    private boolean isHavePermission;

    private List<String> mPermissions =
            new LinkedList<>(
                    Arrays.asList(
                            SystemPermission.WRITE_USER_STORAGE, SystemPermission.CAMERA, SystemPermission.MICROPHONE));


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        Ability ability = getAbility();
        if (ability instanceof MainAbility) {
            ((MainAbility) ability).setPermissionListener(this);
        }
        getWindow().setTransparent(true);
        Component component = findComponentById(ResourceTable.Id_jcameraview);
        if (component instanceof JCameraView) {
            mJCameraView = (JCameraView) component;
            mJCameraView.switchToBackCamera();
            mJCameraView.setSaveVideoPath(getExternalMediaDirs()[0].getAbsolutePath());
            mJCameraView.setIconLeftAndRight(
                    ResUtils.getVectorDrawable(getAbility(), ResourceTable.Graphic_ic_back),
                    ResUtils.getVectorDrawable(getAbility(), ResourceTable.Graphic_ic_photo));
            mJCameraView.setErrorListener(
                    (errorString, type) -> LogUtil.error(LogUtil.DEFAULT_TAG, "errorString:" + errorString));
            mJCameraView.setJCameraListener(
                    new JCameraListener() {
                        @Override
                        public void captureSuccess(PixelMap bitmap) {
                            String fileUrl = FileUtil.saveBitmap("JCamera", bitmap, getContext());
                            backToWelcomeAbilitySlice(fileUrl);
                        }

                        @Override
                        public void recordSuccess(String url) {
                            LogUtil.error(LogUtil.DEFAULT_TAG, "recordSuccess");
                            backToWelcomeAbilitySlice(url);
                        }
                    });
            mJCameraView.setLeftClickListener(
                    () -> {
                        setResult(new Intent());
                        terminate();
                    });
            mJCameraView.setRightClickListener(() -> LogUtil.info(LogUtil.DEFAULT_TAG, "Click Right"));
            reqPermissions();
        }
    }

    private void reqPermissions() {
        mPermissions.removeIf(perS -> verifySelfPermission(perS) == PERMISSION_GRANTED || !canRequestPermission(perS));
        if (mPermissions.isEmpty()) {
            isHavePermission = true;
        }
    }

    private void handCamera() {
        isHavePermission = false;
        LogUtil.error(LogUtil.DEFAULT_TAG, "handCamera");
        if (mJCameraView != null) {
            mJCameraView.onResume();
        }
    }

    @Override
    protected void onBackPressed() {
        super.onBackPressed();
        LogUtil.error(LogUtil.DEFAULT_TAG, "onBackPressed");
        setResult(new Intent());
        mJCameraView.switchToBackCamera();
    }

    @Override
    public void onReqFinish() {
        isHavePermission = true;
        handCamera();
    }

    @Override
    public void onActive() {
        super.onActive();
        handCamera();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
        if (mJCameraView != null) {
            mJCameraView.onPause();
        }
    }

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        int width = 0;
        int height = 0;
        if (ScreenUtils.isVerticalScreen(this)) {
            width = ScreenUtils.getFullScreenWidth(this);
            height = ScreenUtils.getFullScreenHeight(this);
        } else {
            width = ScreenUtils.getFullScreenHeight(this);
            height = ScreenUtils.getFullScreenWidth(this);
        }
        StackLayout.LayoutConfig params = new StackLayout.LayoutConfig(width, height);
        mJCameraView.getSurfaceProvider().setLayoutConfig(params);
    }

    /**
     * 通知系统相册扫描新保存的图片
     * @param imgPath 路径
     */
    private void notifyGalleryToScan(String imgPath) {
        Operation operation = new Intent.OperationBuilder().withAction(ACTION_MEDIA_SCANNER_SCAN_FILE).build();
        Intent mediaScanIntent = new Intent();
        mediaScanIntent.setOperation(operation);
        Uri uri = Uri.getUriFromFile(new File(imgPath));
        mediaScanIntent.setUri(uri);
        CommonEventData eventData = new CommonEventData(mediaScanIntent);
        try {
            CommonEventManager.publishCommonEvent(eventData);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void backToWelcomeAbilitySlice(String fileUrl) {
        notifyGalleryToScan(fileUrl);
        Intent fileIntent = new Intent();
        fileIntent.setParam("PHOTO_URL", fileUrl);
        setResult(fileIntent);
        terminate();
    }
}
